#!/usr/bin/python
# -*- coding: UTF-8 -*-

import re
import os
import sys

# 工作目录
address = '/root/openharmony/master/'
# 软件大目录或精确目录
file = 'tp_list.txt'
# 扫描字段
ScanFields = ["Name", "Version Number", "License", "License File", "Owner", "Upstream URL", "Description"]
# 存储软件目录表单
lists = []
# 存储输出列表
output = []


def get_text(text, num=3):
    # 取引号内的字符串
    start_text = text.find('"')
    if start_text == -1:
        return ""
    if num == 3:
        for i in range(2): start_text = text.find('"', start_text + 1)
    elif num == 2:
        start_text = text.find('"', start_text + 1)
    elif num == 1:
        pass
    else:
        sys.exit()
    end_text = text.find('"', start_text + 1)
    return_text = text[start_text + 1: end_text]  # 截取字符串
    return_text = re.sub(r'^[ \t\n]*|[ \t\n]*$', '', return_text)
    return return_text


def get_line1(files, text):
    # 读取第一行含关键字的行
    with open(files, 'r') as lines:
        for line in lines:
            if text in line:
                return line
        return ""


def get_list():
    # 初始化软件列表,相对目录
    aaa = []
    bbb = []
    with open(file, 'r') as lines:
        for line in lines:
            if "list1" in line: aaa.append(get_text(line))
            elif "list2" in line: bbb.append(get_text(line))
            else: pass
    for i in aaa:
        if i == "": continue
        diroflist = os.listdir(address + i)
        for j in diroflist:
            dir_file_path = os.path.join(address + i, j)
            if os.path.isdir(dir_file_path):
                lists.append(i + "/" + j)
    for i in bbb:
        if i == "": continue
        lists.append(i + "/")


def get_line2(files, text):
    # 读取多行含关键字的行
    lists1 = []
    with open(files, 'r') as lines:
        for line in lines:
            if text in line and "#" not in line: lists1.append(line)
        return lists1


def final():
    # 扫描文件
    for i in lists:
        final1 = [i]
        for j in ScanFields:
            my_file = address + i + "/README.OpenSource"
            if os.path.exists(my_file):
                final1.append(get_text(get_line1(my_file, j)))
            else: final1.append("")
        output.append(final1)


def to_excel():
    from openpyxl import Workbook
    # 创建一个workbook
    wb = Workbook()
    # 获取被激活的worksheet
    ws = wb.active
    wws = ['Directory']
    for i in ScanFields:
        wws.append(i)
    ws.append(wws)
    for j in output:
        ws.append(j)
    wb.save('output.xlsx')


def run():
    # main
    get_list()
    # print(lists)
    final()
    # print(output)
    to_excel()


if __name__ == '__main__':
    run()
